package cn.gson.crm.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.alibaba.fastjson.JSONObject;

import cn.gson.crm.model.dao.EmployeeDao;
import cn.gson.crm.model.entity.Employee;
import cn.gson.crm.model.entity.Resource;

/**
 *
 * @author hzl
 * @date 2018年4月15日
 * @time 上午10:11:34
*/
@Controller
@RequestMapping("crm/login")
public class LoginController {
	@Autowired
	EmployeeDao empDao;
	@GetMapping
	public String index(){
		return "login";
	}
	@PostMapping("dologin")
	public String dologin(@RequestParam String empName, @RequestParam String password, HttpSession session,
			RedirectAttributes r){
		Employee emp = empDao.findOneByEmpName(empName);
		if (emp != null && emp.isState() && emp.getPassword().equals(password)) {
//		if (emp != null && emp.isState() && emp.getPassword().equals(DigestUtils.md2Hex(password))) {
			session.setAttribute("employee", emp);
			//保存当前登录的角色名称，用于各个地方的角色判断
			session.setAttribute("roleName", emp.getRole().getRoleName());
			
			Set<Resource> resources = new HashSet<>();
			try {
				resources.addAll(emp.getRole().getResources());
			} catch (Exception e) {
				System.out.println("没有角色");
			}

			// 取出菜单
			List<Resource> menus = new ArrayList<>();
			Set<String> urls = new HashSet<>();
			Set<String> identifys = new HashSet<>();
			resources.forEach(resource -> {
				if (resource.getType().equals(Resource.Type.MENU)) {
					menus.add(resource);
				}

				identifys.add(resource.getIdentify());
				if (!StringUtils.isEmpty(resource.getUrls())) {
					urls.addAll(Arrays.asList(resource.getUrls().split(",")));
				}
			});

			List<Resource> tree = new ArrayList<>();
			menus.forEach(rs -> {
				if (rs.getParent() == null) {
					this.recursion(menus, rs);
					tree.add(rs);
				}
			});
			// 将权限相关的所有信息存入 session
			session.setAttribute("menus", tree);
			session.setAttribute("urls", urls);
			session.setAttribute("identifys", identifys);

			return "redirect:../../crm/main";
		}
		// 重定向参数
		r.addFlashAttribute("err", "帐号或密码错误!");
		return "redirect:/crm/login";
	}
	@PostMapping("doajaxlogin")
	@ResponseBody
	public JSONObject doajaxlogin(@RequestParam String empName, @RequestParam String password, HttpSession session){
		session.removeAttribute("employee");
		JSONObject jsonObject = new JSONObject();
		Employee emp = empDao.findOneByEmpName(empName);
		if(emp==null){
			jsonObject.put("err", "用户不存在！");
		}else if (emp != null && emp.isState() && emp.getPassword().equals(password)) {
//		if (emp != null && emp.isState() && emp.getPassword().equals(DigestUtils.md2Hex(password))) {
			session.setAttribute("employee", emp);
			//保存当前登录的角色名称，用于各个地方的角色判断
			session.setAttribute("roleName", emp.getRole().getRoleName());
			jsonObject.put("success", "登录成功!");
		}else{
			jsonObject.put("err", "登录失败!请检查登录的账号或密码。");
		}
		return jsonObject;
	}		

		
	private void recursion(List<Resource> menus, Resource parent) {
		List<Resource> children = new ArrayList<>();
		menus.forEach(rs2 -> {
			if (rs2.getParent() != null && parent.getId() == rs2.getParent().getId()) {
				this.recursion(menus, rs2);
				children.add(rs2);
			}
		});
		parent.setChildren(children);
	}
	@GetMapping("logout")
	public String logout(HttpSession session) {
		session.invalidate();
		return "redirect:/crm/login";
	}
}
